import storage from 'store'
import {sysUserLogin, getSysUserById} from "../../api/system";
import { getRights } from "../../api/system";
import {ACCESS_TOKEN, MERCHANT_ID} from "../types";

const user = {
  state: {
    info: '',
    token: '',
    menuRights: '',
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_MENU_RIGHTS: (state, menuRights) => {
      state.menuRights = menuRights
    }
  },
  actions: {
    Login({ commit, state }, userInfo) {
     return new Promise((resolve, reject) => {
       sysUserLogin(userInfo).then(res => {
         if (res.code > 0) {
           const result = res.data.sysUser
           if(result.merchantId === storage.get(MERCHANT_ID)) {
             storage.set(ACCESS_TOKEN, result.id, 7 * 24 * 60 * 60 * 1000)
             commit('SET_TOKEN', result.id)
             resolve({success: res.success})
           } else {
             resolve({success: false, message: '账号不存在'})
           }
         } else {
           resolve(res)
         }
       }).catch(error => {
         reject({success:false, message: error})
       })
     })
    },

    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getSysUserById({id: storage.get(ACCESS_TOKEN)}).then(result => {
          const userInfo = result.data.sysUser;
          if (userInfo.id && userInfo.state === 1) {
            commit('SET_INFO', userInfo)
            resolve()
          } else {
            reject(new Error('信息获取错误'))
          }
        })
      })
    },

    GetMenuRights({ commit,state }) {
      return new Promise((resolve, reject) => {
        getRights(state.info.id).then(result => {
          const rights = result.data.rights;
          if (rights) {
            commit('SET_MENU_RIGHTS', rights)
            resolve()
          } else {
            reject(new Error('获取菜单失败'))
          }
        })
      })
    },

    Logout({ commit }) {
      return new Promise((resolve) => {
        resolve()
        commit('SET_TOKEN', '')
        commit('SET_INFO', '')
        storage.remove(ACCESS_TOKEN)
      })
    },
  }
}

export default user
